import {
  ConfirmModel
} from "../../../models/confirm";
import {
  PayModel
} from '../../../models/pay'
import {
  Format
} from '../../../utils/common'
import {
  Common
}
from "../../../utils/common";
import {
  AccountModel
} from '../../../models/account'
import {
  OilModel
} from '../../../models/oil'
const oilmodel = new OilModel()
import {
  MyModel
} from '../../../models/my'

const myModel = new MyModel()
const accountmodel = new AccountModel()
const app = getApp();
const confirmModel = new ConfirmModel()
const payModel = new PayModel()
const format = new Format()
const common = new Common()
Page({
    data: {
      TipTxtTwo: {
        tittle: '会员卡余额不足，请充值后继续支付',
        leftBtn: '再看看',
        rightBtn: '立即充值'
      }, // 位置授权拒绝后弹窗内容
      openTipPopTwoBtn: false, //是否显示位置授权拒绝后弹窗
      openTipPop: false, //提示弹窗
      TipTxt: '', //提示弹窗内容
      tips: '', //跳转判
      btnDisabled: true,
      openPawPop: false,
      gettruePaw: '',
      user: '' , //用户信息
      station: '', //油站信息
      payItem: '', // 上页带来信息
      radioitems: [
        {name: '支付宝', value: 1, checked: true, icon: '/assets/payIcon2.jpg',arrowType: 'success-o'},
        {name: '壳牌会员卡', value: 3, icon: '/assets/payIcon3.png',arrowType: 'circle'}
      ],
      payTypeIndex: 0, // 选择支付方式  
      tradeType: 1, // 支付方式 
      paymentItem: '' , // 收单内容
      cardPaymentItem: '', //会员卡收单内容
      balance: '', // 账余额
      openIfmemberpop: false, // 是否显示选择会员状态弹窗
      showConsume: false, // 是否显示选择会员状态弹窗-是否显示一键加油或者直接战舰
      firstClick: true,
      termNum: '', //设备号
      cardDisAmount: '', //会员卡创建订单优惠金额
      aliDisAmount: '', //支付宝创建订单优惠金额
    },
    onLoad(options) {
        this.setData({
          'payItem': JSON.parse(options.tradeData),
          firstClick: true,
          user: app.globalData.user,
          'station': app.globalData.station,
        })
        // if (options.typeName) {

        // } else {
          this.createOrder('select')
        // }
        console.log(this.data.payItem)
        // this.setData({
        //   firstClick: true,
        //   user: app.globalData.user,
        //   'station': app.globalData.station,
        // })
        // this.createOrder('select')
    },
    onShow: function (options) {
      this.setData({
        firstClick: true,
        user: app.globalData.user,
        'station': app.globalData.station,
      })
      console.log(this.data.firstClick)
      console.log(this.data.station)
      console.log(this.data.user)
      // if (!this.data.paymentItem) {
      //   this.createOrder('select')
      // }
      if (this.data.user.cardAsn) {
        this.loadMyAccount()
      }
    },
    // 获取账户信息
    loadMyAccount() {
      myModel.loadMyAccount().then(res => {
        console.log(res)
        if (res) {
          if (res.code == '00') {
            this.setData({
              balance: res.result.balance
            })
          } else if (res.message) {
            balance: 0
            // this.setData({
            //   openTipPop: true,
            //   TipTxt: res.message,
            //   tips: 'close',
            // });
          }
        } else {
          this.setData({
            openTipPop: true,
            TipTxt: '获取账户信息失败',
            tips: 'close',
          });
        }
        
      })
    },
    // 选择支付方式
    radioChange: function (e) {
        let vm = this
        let item = e.currentTarget.dataset
        if (item.item.value == 3) {
          if (!this.data.user || !this.data.user.cardAsn) {
            this.setData({
              openIfmemberpop: true
            })
            return
          } else {
            // this.data.balance = 0
            if  (this.data.balance*100 < this.data.payItem.deliveryAmount) {
              vm.setData({
                'openTipPopTwoBtn': true,
              })
              console.log(this.data.openTipPopTwoBtn)
              return
            }
          }
        }
        
        this.selectRadio(item)
    },
    selectRadio: function(item) {
      if (item.item.value == 1) {
        if (this.data.paymentItem) {
          this.setData({
            'payTypeIndex': item.index,
            'tradeType': item.item.value,
            btnDisabled: false,
          });
          return
        } else {
          this.createOrder('select',item)
        }
      } else {
        if (this.data.cardPaymentItem) {
          this.setData({
            'payTypeIndex': item.index,
            'tradeType': item.item.value,
            btnDisabled: false,
          });
          return
        } else {
          this.createOrder('select',item)
        }
      }
    },
    // 创建订单
    createOrder(type,item) {
      let vm = this
      console.log(this.data.firstClick)
      if (this.data.firstClick) {
        this.setData({
          firstClick: false,
        });
      } else {
        return
      }
      let tradeType = ''
      if(item) {
        tradeType = item.item.value
      } else {
        tradeType = this.data.tradeType
      }

      let user = vm.data.user
      let station = vm.data.station
      let payItem = vm.data.payItem
      let parms= {
        shopId: station.alipay_store_id,
        deliveryId: payItem.deliveryId,
        modelPhone: (user.phone || ''),
        cardSn: (user.cardAsn || ''),
        oilGunNo: payItem.oilGun,
        deliveryCode: payItem.deliveryCode,
        deliveryCodeName: payItem.deliveryCodeName,
        deliveryVolume: payItem.deliveryVolume,
        deliveryAmount: payItem.deliveryAmount,
        deliveryPrice: payItem.deliveryPrice,
        jiayouSource: station.myjy_source,
        payType:  tradeType,
      }
      oilmodel.createTrade(parms).then(res => {
        if (res) {
          if (res.code == '00') {
            parms.orderId = res.orderId
            parms.deliveryId = res.deliveryId
            parms.discount = res.discount
            parms.realAmount = res.realAmount
            if (item) {
              if (item.item.value  == 1) {
                vm.setData({
                  paymentItem: parms,
                  btnDisabled: false,
                  'payTypeIndex': item.index,
                  'tradeType': item.item.value,
                  firstClick: true,
                });
                // vm.setData({
                //   aliDisAmount: res.discount,
                // });
              } else {
                vm.setData({
                  cardPaymentItem: parms,
                  btnDisabled: false,
                  'payTypeIndex': item.index,
                  'tradeType': item.item.value,
                  firstClick: true,
                });
                // vm.setData({
                //   cardDisAmount: res.discount,
                // });
              }
              
            } else {
              vm.setData({
                paymentItem: parms,
                firstClick: true,
                // aliDisAmount: res.discount,
                btnDisabled: false,
              })
            }
            console.log(this.data.paymentItem)
          } else {
            if (item) {
              this.setData({
                firstClick: true,
                btnDisabled: true,
                openTipPop: true,
                TipTxt: (res.message || '下单失败'),
                tips: 'close',
              });
            } else {
              this.setData({
                firstClick: true,
                btnDisabled: true,
                openTipPop: true,
                TipTxt: (res.message || '下单失败'),
                tips: 'close',
              });
            }
          }
        } else {
          if (item) {
            this.setData({
              firstClick: true,
              btnDisabled: true,
              openTipPop: true,
              TipTxt: '下单失败',
              tips: 'close',
            });
          } else {
            this.setData({
              firstClick: true,
              btnDisabled: true,
              openTipPop: true,
              TipTxt: '下单失败',
              tips: 'close',
            });
          }
          
        }
      });
    },
    clickNext() {
      let vm = this
      if (this.data.firstClick) {
        this.setData({
          firstClick: false,
        });
      } else {
        return
      }
      let user = vm.data.user
      if (vm.data.tradeType == 1) {
        vm.paymentRequest()
      } else {
        if (user.activityStatus && user.activityStatus == 2) {
          this.setData({
            openPawPop: true,
          });
        } else {
          this.setData({
            modalOpened4: true,
          })
        }
        console.log(vm.data.tradeType)
      }
    },
    // 统一收单接口
    paymentRequest(payPassword) {
      let vm = this
      let paymentItem = ''
      if (this.data.tradeType == 1) {
        paymentItem = vm.data.paymentItem
      } else {
        paymentItem = vm.data.cardPaymentItem
      }
      let station = vm.data.station
      let parms= {
        shopId: paymentItem.shopId,
        payPassword: (payPassword || ''),
        modelPhone: paymentItem.modelPhone,
        cardSn: paymentItem.cardAsn,
        orderId: paymentItem.orderId,
        deliveryId: paymentItem.deliveryId,
        payType: paymentItem.payType,
        oilGunNo: paymentItem.oilGunNo,
        subject: station.name,
        amount: paymentItem.deliveryAmount,
        realAmount: (paymentItem.realAmount || ''),
        jiayouSource: paymentItem.jiayouSource,
        termNum: this.data.termNum,
      }
      oilmodel.paymentRequest(parms).then(res => {
        if (res) {
          if (res.code == '00') {
            this.setData({
              termNum: res.termNum || ''
            })
            // parms.orderId = res.orderId
            // parms.deliveryId = res.deliveryId
            // parms.discount = res.discount
            // parms.realAmount = res.realAmount
            // this.data.paymentItem = parms
            if (vm.data.tradeType == 1) {
              vm.setData({
                firstClick: true,
              });
              payModel.myPay('consume',res.tradeNo,'','',res.orderId)
            } else {
              my.redirectTo({
                url: '/pages/oil/oilResult/oilResult?tradeNo=' + res.tradeNo + '&yhorderID=' + res.orderId
              })
              console.log(vm.data.tradeType)
            }
          } else {
            this.setData({
              termNum: res.termNum || '',
              openTipPop: true,
              TipTxt: (res.message || '下单失败'),
              tips: 'close',
            });
          }
        } else {
          this.setData({
            openTipPop: true,
            TipTxt: '下单失败',
            tips: 'close',
          });
        }
      });
    },
    // 关掉是否会员弹窗
    onClose() {
      this.setData({
        firstClick: true,
        openIfmemberpop: false,
      });
    },
    // 会员卡支付
    gocardPay(paw) {
      this.paymentRequest(paw)
      console.log(paw + '~~~~~~~~~~~~')
    },
    
    //  关闭输入会员卡密码弹窗
    closePawPop() {
      this.setData({
        firstClick: true,
        openPawPop: false
      })
    },
    // 关闭双按钮弹窗
    tipPopCloseTwoBtn() {
      this.setData({
        firstClick: true,
        openTipPopTwoBtn: false,
      });
    },
    // 跳转充值
    tipPopSureTwoBtn() {
      my.navigateTo({
        url: '/pages/recharge/recharge/recharge?href=oilConfirm'
      })
      this.setData({
        openTipPopTwoBtn: false,
      });
    },
    // 点击公共弹窗知道了
    tipPopSure(tips) {
      this.setData({
        firstClick: true,
        openTipPop: false
      });
      if (tips == 'href') {
        my.navigateBack('1')
      }
    },
    toPay() {
        const d = this.data.payItem
        // this.createTradeNew('')
        if (d.payType == 1) {
          this.createTradeNew('')
        } else {
          if (app.globalData.ifSetPaw == 0) {
            this.setData({
                modalOpened4: true,
            });
          } else if (app.globalData.ifSetPaw == 1) {
            this.setData({
              openPawPop: true
            })
          } else {
            this.checkOriginPwd()
          }
        }
        // if (d.tradeType == 1) {
          // payModel.createTradeNew(d.tradeType,d.amount, d.realAmount, d.subject, d.shopId, d.jiayouSource,d.orderId,d.goodsId,d.oilGunId).then(res => {
          //   console.log(res)
          //   if (res && res.orderId) {
          //       if (d.tradeType == 1) {
          //         payModel.myPay('consume',res.tradeNo, d.realAmount, d.canUseTicketAmount, d.gunNum, d.oilNum)
          //       } else {
          //         my.redirectTo({
          //           url: '/pages/finish/finish?tradeNo=' + res.orderId
          //         })
          //       }
          //   } else {
          //     if (res.message) {
          //       console.log(res.message)
          //       my.showToast({
          //         type: 'none',
          //         content: res.message,
          //         duration: 600,
          //       });
          //     } else {
          //       console.log('11111')
          //       my.showToast({
          //         type: 'none',
          //         content: '交易失败，请重试',
          //         duration: 600,
          //       });
          //     }
          //   }
          // });
        // } else {
          // if (app.globalData.ifSetPaw) {
          //   this.setData({
          //     openPawPop: true
          //   })
          // } else {
          //   this.checkOriginPwd()
          // }
        //   
        //   // my.redirectTo({
        //   //   url: '/pages/finish/finish?tradeNo=' + res.orderId
        //   // })
        // }
    },
    createTradeNew(payPassword) {
      const d = this.data.payItem
      payModel.createTradeNew(payPassword,d.payType,d.amount, d.realAmount, d.subject, d.shopId, d.jiayouSource,d.orderId,d.oilGunNo,d.deliveryId).then(res => {
          console.log(res)
        if (res && res.orderId) {
            if (d.payType == 1) {
              payModel.myPay('consume',res.tradeNo, d.realAmount, d.canUseTicketAmount, d.gunNum, d.oilNum)
            } else {
              this.setData({
                openPawPop: false
              })
              my.redirectTo({
                url: '/pages/finish/finish?tradeNo=' + res.orderId
              })
            }
        } else {
          if (res && res.message) {
            console.log(res.message)
            my.showToast({
              type: 'none',
              content: res.message,
              duration: 600,
            });
          } else {
            console.log('11111')
            my.showToast({
              type: 'none',
              content: '交易失败，请重试',
              duration: 600,
            });
          }
        }
      });
    },
    checkOriginPwd() {
      accountmodel.checkOriginPwd().then(res => {
          console.log(res)
          if (res && res.code == '00') {
            if (res.pinStatus == 0) {
              app.globalData.ifSetPaw = 0
              this.setData({
                modalOpened4: true,
              });
            } else {
              app.globalData.ifSetPaw = 1
              this.setData({
                openPawPop: true
              })
            }
          } else {
            my.showToast({
              type: 'none',
              content: '接口错误',
              duration: 1000,
            });
          }
        })
    },
    onModalClick21() {
      this.setData({
        modalOpened4: false,
      });
      my.navigateTo({
        url: '/pages/account/setPaw/setPaw'
      })
    },
    onModalClose21() {
      this.setData({
        firstClick: true,
        modalOpened4: false,
      });
    },
    
    
});